package handler

import (
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/samber/do/v2"

	"gitee.com/monkeyPP/happy-mall/services/userservice/internal/application"
	"gitee.com/monkeyPP/happy-mall/services/userservice/internal/interfaces/api/request"
	"gitee.com/monkeyPP/happy-mall/services/userservice/internal/interfaces/api/response"
)

type AuthHandler interface {
	Refresh(c *gin.Context)
}

type AuthHandlerImpl struct {
	authApp application.AuthApp
}

func NewAuthHandler(i do.Injector) (AuthHandler, error) {
	authApp := do.MustInvoke[application.AuthApp](i)
	return &AuthHandlerImpl{
		authApp: authApp,
	}, nil
}

func (ah *AuthHandlerImpl) Refresh(c *gin.Context) {
	var req request.TokenRefreshRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	tokenPair, err := ah.authApp.Refresh(c, req.RefreshToken)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"token": response.UserLoginResponse{
			AccessToken:  tokenPair.AccessToken,
			RefreshToken: tokenPair.RefreshToken,
		},
	})
}
